﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Sector7.Medical.EntityType;
using Sector7.Framework.Utility;
using System.ComponentModel;
using Sector7.Medical.Biz;
using Sector7.Medical.Consts;
using Sector7.Framework.Core;
using Sector7.Framework.Enums;
using Sector7.Medical.Controls;

namespace Sector7.Medical.INFM.Controls
{
    /// <summary>
    /// ChargeItemSummaryControl.xaml 的交互逻辑
    /// </summary>
    public partial class ChargeItemSummaryControl : SummaryControlBase
    {
        #region Accessor
        public M7_ChargeItem ChargeItem
        {
            get { return m_entity as M7_ChargeItem; }
            set { m_entity = value; }
        }
        #endregion

        #region Public functions
        #endregion

        #region Private functions
        private void LoadData()
        {
            ClientUtil.LoadItemsSource(dtgMain, m_itemList);
            ClientUtil.LoadItemsSource(cbbDeptList, m_depts);

            Senvironments.ProgressWindow.Visibility = Visibility.Hidden;
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            Senvironments.ProgressWindow.Visibility = Visibility.Visible;
            SwitchProperityGroupEnableState(false);

            var worker = BackgroundWorkerUtil.GetWorker(this);
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            worker.RunWorkerAsync();
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            m_itemList = Agent_INFS.GetChargeItemList();
            m_depts = Agent_INFS.GetDepartmentList(C_DepartmentFlags.CAN_CHARGE);

            this.Dispatcher.BeginInvoke(new DelegateWithNothing(LoadData));
        }

        private void SwitchProperityGroupEnableState(bool isEnable)
        {
            txbItemId.IsEnabled = false;
            txbItemName.IsEnabled = isEnable;
            txbPrice.IsEnabled = isEnable;
            cbbDeptList.IsEnabled = isEnable;
            ckbIsValid.IsEnabled = isEnable;
        }

        private void dtgMain_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selectedItem = dtgMain.SelectedItem as M7_ChargeItem;
            if (selectedItem != null)
            {
                SetDetailControls(selectedItem);
                SwitchEditableButtonsStatus(CrudType.Read);
                SwitchProperityGroupEnableState(false);
            }
            else
            {
                ResetDetailControls();
                SwitchEditableButtonsStatus(CrudType.Create);
            }
        }

        /// <summary>
        /// 选中Item颜色改变
        /// </summary>
        /// <param name="area"></param>
        private void SelectRoomItem(M7_ChargeItem item)
        {
            if (dtgMain.Items.Contains(item))
            {
                dtgMain.SelectedItem = item;
            }
        }

        protected override void SetDetailControls(object entity)
        {
            M7_ChargeItem item = entity as M7_ChargeItem;

            if (item != null)
            {
                txbItemId.Text = item.ChargeItemId.ToString();
                txbItemName.Text = item.ChargeItemName;
                txbPrice.Text = item.Price.ToString();
                cbbDeptList.SelectedValue = item.DeptId;
                ckbIsValid.IsChecked = (item.Flags & C_ChargeItemFlags.INVALID) == C_ChargeItemFlags.INVALID ? false : true;
            }
        }

        protected override void ResetDetailControls()
        {
            txbItemId.Text = string.Empty;
            txbItemName.Text = string.Empty;
            txbPrice.Text = string.Empty;
            cbbDeptList.SelectedIndex = 0;
            ckbIsValid.IsChecked = false;
        }

        private bool CheckData()
        {
            m_errors.Clear();

            string ItemName = txbItemName.Text.Trim();
            decimal price = -1;
            //bool priceValid = RegularUtil.IsDecimal(price);
            int deptId = (cbbDeptList.SelectedItem as M7_Department).DeptId;

            if (string.IsNullOrEmpty(ItemName))
            {
                m_errors.Add("收费项名称", "不能为空!");
            }

            try
            {
                price = Convert.ToDecimal(txbPrice.Text.Trim());
            }
            catch
            {
                m_errors.Add("费用", "请输入数字或小数!");
            }
            //if (!priceValid)
            //{
            //    m_errors.Add("费用", "请输入数字或小数!");
            //}

            if (deptId < 0)
            {
                m_errors.Add("科室", "请选择科室!");
            }

            return base.CheckData();
        }

        private void AddData()
        {
            if (m_crud == CrudType.Update)
            {
                var selectedItem = dtgMain.SelectedItem as M7_ChargeItem;
                ChargeItem.ChargeItemId = selectedItem.ChargeItemId;
            }
            else
            {
                ChargeItem = new M7_ChargeItem();
            }

            ChargeItem.ChargeItemName = txbItemName.Text;
            ChargeItem.Price = Convert.ToDecimal(txbPrice.Text);
            ChargeItem.DeptId = (cbbDeptList.SelectedItem as M7_Department).DeptId;
            ChargeItem.Flags = Convert.ToInt32(ckbIsValid.IsChecked);
        }

        protected override void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            InitializeControl(CrudType.Create);
            SwitchProperityGroupEnableState(true);
            base.btnAdd_Click(sender, e);
        }

        protected override void btnModify_Click(object sender, RoutedEventArgs e)
        {
            if (dtgMain.SelectedItem != null && dtgMain.SelectedItem is M7_ChargeItem)
            {
                var item = dtgMain.SelectedItem as M7_ChargeItem;
                ChargeItem = item;
                InitializeControl(CrudType.Update);
                SwitchProperityGroupEnableState(true);
            }
            base.btnModify_Click(sender, e);
        }

        protected override void btnOk_Click(object sender, RoutedEventArgs e)
        {
            if (!CheckData())
            {
                ShowErrors();
            }
            else
            {
                AddData();
                switch (m_crud)
                {
                    case CrudType.Create:
                        object itemId = Agent_INFS.AddChargeItem(ChargeItem);
                        if (itemId != null)
                        {
                            ChargeItem.ChargeItemId = Convert.ToInt32(itemId);
                            m_itemList.Add(ChargeItem);
                            dtgMain.Items.Refresh();
                        }
                        break;
                    case CrudType.Update:
                        bool isChanged = false;
                        var delta = GetDelta("ChargeItemId", ref isChanged);
                        if (isChanged)
                        {
                            Agent_INFS.UpdateChargeItem(delta);
                            dtgMain.Items.Refresh();
                        }
                        break;
                    default:
                        break;
                }
            }
            //base.btnOk_Click(sender, e);
        }

        protected override void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            var selectItem = dtgMain.SelectedItem as M7_ChargeItem;
            if (selectItem != null)
            { 
                MessageBoxResult mbr = Alert.ShowDialog(AlertType.Question, "是否确定删除该收费项?");
                if (mbr == MessageBoxResult.Yes)
                {
                    int ret = Agent_INFS.DeleteChargeItem(selectItem.ChargeItemId);
                    if (ret > 0)
                    {
                        if (m_itemList.Contains(selectItem))
                        {
                            m_itemList.Remove(selectItem);
                            dtgMain.Items.Refresh();
                        }
                    }
                }
            }

            base.btnDelete_Click(sender, e);
        }

        protected override void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            var selectedItem = dtgMain.SelectedItem as M7_ChargeItem;

            if(selectedItem != null)
            {
                SetDetailControls(selectedItem);
                SwitchProperityGroupEnableState(false);
            }
            base.btnCancel_Click(sender, e);
        }

        protected override void InitializeForCreating()
        {
            ResetDetailControls();
            base.InitializeForCreating();
        }

        protected override void InitializeForUpdating()
        {
            SetDetailControls(ChargeItem);
            base.InitializeForUpdating();
        }
        #endregion

        #region Structure
        public ChargeItemSummaryControl()
        {
            InitializeComponent();

            m_btnAdd = btnAdd;
            m_btnModify = btnModify;
            m_btnDelete = btnDelete;
            m_btnOk = btnOk;
            m_btnCancel = btnCancel;
        }
        #endregion

        #region Inner members
        /// <summary>
        /// 获取所有收费项列表
        /// </summary>
        private List<M7_ChargeItem> m_itemList = null;
        
        /// <summary>
        /// 获取所有科室列表
        /// </summary>
        private List<M7_Department> m_depts = null;
        #endregion
    }
}
